package com.opages.mvc.adapter.common.client.serviceregistry;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.concurrent.atomic.AtomicBoolean;

public abstract class AbstractAutoServiceRegistration<R extends Registration> implements AutoServiceRegistration , ApplicationListener<ContextRefreshedEvent> {
	private volatile AtomicBoolean isInit = new AtomicBoolean(false);
	private final ServiceRegistry<R> serviceRegistry;

	public AbstractAutoServiceRegistration(ServiceRegistry<R> serviceRegistry) {
		super();
		this.serviceRegistry = serviceRegistry;
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
		//防止重复触发
		if(!isInit.compareAndSet(false,true)) {
			return;
		}
		this.serviceRegistry.register(getRegistration());
	}

	protected abstract R getRegistration();
}
